package org.example.gateway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import org.example.gateway.bean.App;
import org.example.gateway.bean.AppInstance;
import org.example.gateway.mapper.AppInstanceMapper;
import org.example.gateway.mapper.AppMapper;
import org.example.gateway.pojo.UpdateWeightDto;
import org.example.gateway.pojo.vo.InstanceVo;
import org.example.gateway.service.AppInstanceService;
import org.example.gateway.transfer.InstanceVoTransfer;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AppInstanceImpl implements AppInstanceService {
    @Resource
    private AppInstanceMapper instanceMapper;
    @Resource
    private AppMapper appMapper;

    @Override
    public List<InstanceVo> queryList(Integer appId) {
        App app = appMapper.selectById(appId);
        QueryWrapper<AppInstance> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AppInstance::getAppId, appId);
        List<AppInstance> instances = instanceMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(instances)) {
            return Lists.newArrayList();
        }
        List<InstanceVo> instanceVos = InstanceVoTransfer.INSTANCE.mapToVos(instances);
        instanceVos.forEach(vo -> vo.setAppName(app.getAppName()));
        return instanceVos;
    }

    @Override
    public void updateWeight(UpdateWeightDto updateWeightDto) {
        AppInstance instance = new AppInstance();
        instance.setId(updateWeightDto.getId());
        instance.setWeight(updateWeightDto.getWeight());
        instanceMapper.updateById(instance);
    }
}
